<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1,maximum-scale=1.0,minimum-scale=1">
    <title>探测 - {{ target.getTitle() }}</title>
    <script src="https://cdn.bootcss.com/echarts/3.4.0/echarts.min.js"></script>
	<style>body,html { margin: 0, padding: 0 }</style>
</head>
<body>

   <div id="main"></div>
    <script type="text/javascript">

		document.getElementById('main').style.width = window.innerWidth - 20 + 'px';
		document.getElementById('main').style.height = window.innerHeight - 20 + 'px';

		window.onresize = function() {
			document.getElementById('main').style.width = window.innerWidth + 'px';
			document.getElementById('main').style.height = window.innerHeight + 'px';
		}

		var xdata = []
		var ydata = [];
		var avg	  = [];

        var myChart = echarts.init(document.getElementById('main'));

		var url   = "/target/detect/" + {{ target.getId() }};
        var turl  = "{{ target.getUrl() }}";
        var title = "{{ target.getTitle() }}";

		request();
		setInterval(() => { request() }, {{ target.getTiming() }} * 1000);


		function request() {
			var request = new Request(url, {
				method: 'POST',
				credentials: 'include'
			});
			fetch(request).then(response => {
				if (response.ok) {
					return response.json();
				}
			}).then(json => {
				makeData(json.results[0].duration)
			});
		}		

		function makeData(duration) {

			var now = new Date();
			var nowStr = now.getHours() + '时' + now.getMinutes() + '分' + now.getSeconds() + '秒';
					
			xdata.push(nowStr);
			ydata.push(duration);
			
			var _avg = 0;
			ydata.forEach(d => { _avg += d;  });
			_avg /= ydata.length;

			if (ydata.length > 20) {
				ydata.shift();
				xdata.shift();
				avg.shift();
			}
			
			avg.push(_avg);
			

			option = {
				title: {
					text:  title,
					subtext: turl
				},
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					data:['响应时间', '平均响应时间']
				},

				toolbox: {
					show: true,
					feature: {
						dataZoom: {
							yAxisIndex: 'none'
						},
						dataView: {readOnly: false},
						magicType: {type: ['line', 'bar']},
						restore: {},
						saveAsImage: {}
					}
				},
				xAxis:  {
					type: 'category',
					boundaryGap: false,
					data: xdata
				},
				yAxis: {
					type: 'value',
					axisLabel: {
						formatter: '{value} 秒'
					}
				},
				series: [
					{
						name:'响应时间',
						type:'line',
						data:ydata,
						markPoint: {
							data: [
								{type: 'max', name: '最大值'},
								{type: 'min', name: '最小值'}
							]
						},
					},
					{
						name: '平均响应时间',
						type: 'line',	
						data: avg
					}
				]
			};


			myChart.setOption(option);
		}


	</script>

</body>
</html>
